package com.alphawavesgames.engine.game;

import com.alphawavesgames.engine.rendering.RenderContainer;
import com.alphawavesgames.engine.rendering.SceneRenderer;

/**
 *
 * @author Duncan
 */
public class GameThread extends Thread
{
    private GameContainer m_gameInterface;
    private RenderContainer m_renderContainer;
    private boolean m_running;

    private SceneRenderer m_sceneRenderer;

    public GameThread( GameContainer gameInterface, RenderContainer renderContainer )
    {
        m_gameInterface = gameInterface;
        m_renderContainer = renderContainer;
        m_running = true;
        m_sceneRenderer = null;
    }

    public void initialise( SceneRenderer sceneRenderer )
    {
        m_sceneRenderer = sceneRenderer;
    }

    public void stopRunning()
    {
        m_running = false;
    }

    @Override
    public void run()
    {
        if( m_gameInterface != null )
        {
            //initialise the game before going into the main loop
            m_gameInterface.initialise();

            float frameDelta = 0.0f;
            long lastFrameTimeNano = 0;
            long currTimeNano = System.nanoTime();


            while( m_running )
            {
                lastFrameTimeNano = currTimeNano;
                currTimeNano = System.nanoTime();

                //calc frame delta
                frameDelta = (float)( ( currTimeNano - lastFrameTimeNano ) / 1.0e9 );



                //at the very beginning of a scene we give the rendering engine
                //components a chance to prepare for a new frame.
                //could call this directly from m_sceneRenderer.beginScene()?
                m_renderContainer.beginScene();

                try
                {
                    //perform the main update and render tasks
                    m_gameInterface.update( frameDelta );
                    m_gameInterface.render();
                }
                finally
                {
                    m_renderContainer.endScene();
                }

                if( m_gameInterface.isQuitting() )
                {
                    m_running = false;
                }
            }
        }
    }

}
